<?php
// 开启会话，用于存储游戏数据
session_start();

// 初始化游戏数据
if (!isset($_SESSION['player_hp'])) {
    $_SESSION['player_hp'] = 100;
    $_SESSION['computer_hp'] = 100;
}

// 处理攻击请求
if (isset($_POST['attack'])) {
    // 玩家攻击电脑
    $player_damage = rand(10, 20);
    $_SESSION['computer_hp'] -= $player_damage;
    if ($_SESSION['computer_hp'] < 0) {
        $_SESSION['computer_hp'] = 0;
    }

    // 如果电脑未死亡，电脑进行反击
    if ($_SESSION['computer_hp'] > 0) {
        $computer_damage = rand(10, 20);
        $_SESSION['player_hp'] -= $computer_damage;
        if ($_SESSION['player_hp'] < 0) {
            $_SESSION['player_hp'] = 0;
        }
    }
}

// 处理重新开始请求
if (isset($_POST['restart'])) {
    $_SESSION['player_hp'] = 100;
    $_SESSION['computer_hp'] = 100;
}

// 判断游戏是否结束
$game_over = false;
$winner = "";
if ($_SESSION['player_hp'] <= 0) {
    $game_over = true;
    $winner = "电脑";
} elseif ($_SESSION['computer_hp'] <= 0) {
    $game_over = true;
    $winner = "玩家";
}
?>

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>格斗网页游戏</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
        }

        h1 {
            color: #333;
        }

        #status {
            margin: 20px 0;
            font-size: 18px;
        }

        form {
            margin-top: 20px;
        }

        input[type="submit"] {
            padding: 10px 20px;
            font-size: 16px;
            background-color: #007BFF;
            color: white;
            border: none;
            cursor: pointer;
            margin: 0 10px;
        }

        input[type="submit"]:hover {
            background-color: #0056b3;
        }
    </style>
</head>

<body>
    <h1>格斗网页游戏</h1>
    <div id="status">
        <p>玩家血量: <?php echo $_SESSION['player_hp']; ?></p>
        <p>电脑血量: <?php echo $_SESSION['computer_hp']; ?></p>
        <?php
        if ($game_over) {
            echo "<p>游戏结束！$winner 获胜！</p>";
        }
        ?>
    </div>
    <?php if (!$game_over): ?>
        <form method="post">
            <input type="submit" name="attack" value="攻击">
        </form>
    <?php endif; ?>
    <form method="post">
        <input type="submit" name="restart" value="重新开始">
    </form>
</body>

</html>